package main

import (
	"crypto"
	"crypto/rand"
	"crypto/rsa"
	"crypto/sha256"
	"crypto/x509"
	"encoding/pem"
	"fmt"
	"io/ioutil"
)

// 签名的示例
func main() {
	msg := []byte("verifiable message")
	publicKey := initPubKey()
	privateKey := initPriKey()

	// Before signing, we need to hash our message
	// The hash is what we actually sign
	msgHash := sha256.New()
	_, _ = msgHash.Write(msg)

	msgHashSum := msgHash.Sum(nil)

	// In order to generate the signature, we provide a random number generator,
	// our private key, the hashing algorithm that we used, and the hash sum
	// of our message
	signature, err := rsa.SignPSS(rand.Reader, privateKey, crypto.SHA256, msgHashSum, nil)
	if err != nil {
		panic(err)
	}

	// To verify the signature, we provide the public key, the hashing algorithm
	// the hash sum of our message and the signature we generated previously
	// there is an optional "options" parameter which can omit for now
	err = rsa.VerifyPSS(publicKey, crypto.SHA256, msgHashSum, signature, nil)
	if err != nil {
		fmt.Println("could not verify signature: ", err)
		return
	}
	// If we don't get any error from the `VerifyPSS` method, that means our
	// signature is valid
	fmt.Println("signature verified")

}

func initPubKey() *rsa.PublicKey {
	pubCert, err := ioutil.ReadFile("./client/c101.cert.pem")
	if err != nil {
		fmt.Println(err)
		return nil
	}
	publicKey, err := getPublicKeyFromCert(pubCert)
	if err != nil {
		fmt.Println(err)
		return nil
	}
	return publicKey
}

func initPriKey() *rsa.PrivateKey {
	priPem, err := ioutil.ReadFile("./client/c101.key.pem")
	if err != nil {
		fmt.Println(err)
		return nil
	}
	privateKey, err := getPrivateKey(priPem)
	if err != nil {
		fmt.Println(err)
		return nil
	}
	return privateKey
}

func getPublicKeyFromCert(cert []byte) (publicKey *rsa.PublicKey, err error) {
	block, _ := pem.Decode(cert)

	certificate, err := x509.ParseCertificate(block.Bytes)
	if err != nil {
		fmt.Println(err)
		return
	}

	publicKey = certificate.PublicKey.(*rsa.PublicKey)
	return
}

func getPrivateKey(cert []byte) (privateKey *rsa.PrivateKey, err error) {
	block, _ := pem.Decode(cert)

	privateKey, err = x509.ParsePKCS1PrivateKey(block.Bytes)
	return
}
